package itsm.isperp.module.controller.configuration;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.web.controller.TreeNodeController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.configuration.ConfCategory;
import itsm.isperp.module.service.configuration.ConfCategoryService;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import me.chanjar.weixin.common.util.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 配置分类管理控制器
 * 
 * @author lizx
 * @date 2013-4-30
 */
@Controller
@RequestMapping("configuration/category")
public class ConfCategoryController extends TreeNodeController<ConfCategory> {

	@Autowired
	ConfCategoryService confCategoryService;

	@Override
	public ConfCategoryService getService() {
		return confCategoryService;
	}

	@Override
	public String getPageTitle() {
		return "配置分类";
	}

	@RequestMapping(value = { "inspectManage" })
	public ModelAndView inspectManage(HttpServletRequest req) {
		return this.getModelAndView();
	}
	
	@RequestMapping("listTree")
	@ResponseBody
	public Page<ConfCategory> listTree(String term,
			HttpServletRequest request) {

		if (StringUtils.isNotEmpty(term)) {
			ConfCategoryService confCategoryService = ContextHolder
					.getSpringBean("confCategoryService");
			JqGridRequest req = new JqGridRequest();
			req.addFilterRule("upper(name)", JqGridFilterRuleOp.cn,
					term.toUpperCase());

			req.isPageable(false);
			req.setRows(10);

			return confCategoryService.findAll(req).toPage();

		}
		return null;

	}


	@RequestMapping("getTree")
	@ResponseBody
	@Override
	public List<ConfCategory> getTree(String id, boolean asyncLoad,
			String parentId, boolean showRoot, HttpServletRequest req) {
		if (asyncLoad) {

			JdbcTemplate jdbcTemplate = ContextHolder
					.getSpringBean("jdbcTemplate");

			List<ConfCategory> list = this.getService().getChildren(id,
					showRoot);
			String showNum = req.getParameter("showNum");
			if (showNum == null) {
				showNum = "";
			}
			if (showNum.equals("1")) {

				String sql = "SELECT count(*) FROM conf_ci a INNER JOIN conf_category b  ON a.conf_category_id = b.id WHERE     b.treenode_path LIKE ";

				for (ConfCategory c : list) {
					int count = jdbcTemplate.queryForObject(
							sql + "'%/" + c.getId() + "/%'", Integer.class);

					c.setName(c.getName() + "(<label style='color:blue'>"
							+ count + "</label>)");

				}
			}

			return list;

		}

		return this.getService().getTree(parentId, showRoot);
	}
}
